import { FC, useState, useMemo } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
    Box,
    AppBar,
    Toolbar,
    Drawer,
    List,
    ListItemIcon,
    ListItemText,
    Avatar,
    Typography,
    Menu,
    MenuItem,
    useTheme,
    IconButton,
    Container,
    ListItemButton,
    Tooltip
} from '@mui/material';
import {
    Menu as MenuIcon,
    ChevronLeft as ChevronLeftIcon,
    Person as PersonIcon,
    Settings as SettingsIcon,
    Logout as LogoutIcon,
    People as TeamIcon,
    FileDownload as ExportIcon,
    School as SchoolIcon,
    CloudUpload as ImportIcon
} from '@mui/icons-material';
import './MainLayout.css';
import { usePermission, permissionChangeEvent } from '../contexts/PermissionContext';

// 增加侧边栏宽度以更好地容纳文字
const drawerWidth = 240;
const collapsedWidth = 64;

const MainLayout: FC = () => {
    const location = useLocation();
    const navigate = useNavigate();
    const [collapsed, setCollapsed] = useState(false);
    const currentPath = location.pathname.split('/')[1] || 'dashboard';
    const theme = useTheme();
    const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
    const userMenuOpen = Boolean(anchorEl);

    // 获取用户信息
    const userInfo = useMemo(() => {
        return JSON.parse(localStorage.getItem('userInfo') || '{}');
    }, []);

    // 使用权限上下文
    const { canAccessPermissionPage, canAccessImportPage, canAccessExportPage } = usePermission();

    // 处理用户菜单打开
    const handleUserMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
        setAnchorEl(event.currentTarget);
    };

    // 处理用户菜单关闭
    const handleUserMenuClose = () => {
        setAnchorEl(null);
    };

    // 处理用户菜单点击
    const handleUserMenuClick = () => {
        handleUserMenuClose();
        // 处理登出逻辑
        console.log('用户登出');
        // 清除本地存储中的登录信息
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('uid');
        localStorage.removeItem('displayname');

        // 触发权限变更事件，通知权限上下文更新
        window.dispatchEvent(permissionChangeEvent);

        // 跳转到登录页
        navigate('/login');
    };

    // 侧边栏菜单项配置
    const allMenuItems = [
        {
            key: 'student',
            icon: <TeamIcon />,
            label: '学生信息管理',
            visible: true // 所有用户都可见
        },
        {
            key: 'import',
            icon: <ImportIcon />,
            label: '信息导入管理',
            visible: canAccessImportPage() // 只有管理员和顾问可见
        },
        {
            key: 'export',
            icon: <ExportIcon />,
            label: '信息导出管理',
            visible: canAccessExportPage() // 只有管理员和顾问可见
        },
        {
            key: 'school-recommendation',
            icon: <SchoolIcon />,
            label: '选校推荐',
            visible: true // 所有用户都可见
        },
        {
            key: 'permission',
            icon: <SettingsIcon />,
            label: '权限管理',
            visible: canAccessPermissionPage() // 只有管理员可见
        }
    ];

    // 根据权限过滤菜单项
    const menuItems = allMenuItems.filter((item) => item.visible);

    return (
        <Box sx={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden' }}>
            {/* 顶部导航栏 */}
            <AppBar
                position="fixed"
                sx={{
                    zIndex: (theme) => theme.zIndex.drawer + 1,
                    boxShadow: '0 1px 4px rgba(0, 0, 0, 0.08)',
                    background: '#754fa0'
                }}
                color="default">
                <Toolbar>
                    <IconButton
                        edge="start"
                        color="inherit"
                        onClick={() => setCollapsed(!collapsed)}
                        sx={{ mr: 2, color: 'white' }}>
                        {collapsed ? <ChevronLeftIcon /> : <MenuIcon />}
                    </IconButton>
                    <Typography variant="h6" component="div" sx={{ flexGrow: 1, color: 'white' }}>
                        SME CDC Student Management System
                        <Box component="span" sx={{ color: 'primary.main', marginLeft: 1 }}></Box>
                    </Typography>
                    <Box sx={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }} onClick={handleUserMenuOpen}>
                        <Avatar sx={{ bgcolor: theme.palette.primary.main, marginRight: 1 }}>
                            <PersonIcon />
                        </Avatar>
                        <Typography sx={{ color: 'white', fontWeight: 'bold' }}>{userInfo.display_name}</Typography>
                    </Box>
                    <Menu
                        anchorEl={anchorEl}
                        open={userMenuOpen}
                        onClose={handleUserMenuClose}
                        anchorOrigin={{
                            vertical: 'bottom',
                            horizontal: 'right'
                        }}
                        transformOrigin={{
                            vertical: 'top',
                            horizontal: 'right'
                        }}>
                        <MenuItem onClick={() => handleUserMenuClick()} sx={{ color: 'error.main' }}>
                            <ListItemIcon>
                                <LogoutIcon fontSize="small" color="error" />
                            </ListItemIcon>
                            <ListItemText>退出登录</ListItemText>
                        </MenuItem>
                    </Menu>
                </Toolbar>
            </AppBar>

            {/* 主要内容区域 - 包含工具栏间隔、侧边栏和内容 */}
            <Box sx={{ display: 'flex', flex: 1, pt: '64px', overflow: 'hidden' }}>
                {/* 侧边栏 */}
                <Drawer
                    variant="permanent"
                    sx={{
                        width: collapsed ? collapsedWidth : drawerWidth,
                        flexShrink: 0,
                        '& .MuiDrawer-paper': {
                            position: 'relative',
                            width: collapsed ? collapsedWidth : drawerWidth,
                            boxSizing: 'border-box',
                            boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                            borderRight: '1px solid rgba(0, 0, 0, 0.06)',
                            height: '100%',
                            transition: theme.transitions.create('width', {
                                easing: theme.transitions.easing.sharp,
                                duration: theme.transitions.duration.enteringScreen
                            }),
                            overflowX: 'hidden',
                            top: 'auto', // 取消固定位置
                            marginTop: 0 // 确保没有上边距
                        },
                        whiteSpace: 'nowrap' // 确保文本不会换行
                    }}>
                    <Box sx={{ overflow: 'auto', height: '100%' }}>
                        <List sx={{ width: '100%', padding: 0 }}>
                            {menuItems.map((item) => (
                                <Tooltip
                                    key={item.key}
                                    title={collapsed ? item.label : ''}
                                    placement="right"
                                    arrow
                                    disableHoverListener={!collapsed}>
                                    <ListItemButton
                                        selected={currentPath === item.key}
                                        onClick={() => navigate(`/${item.key}`)}
                                        sx={{
                                            minHeight: 48,
                                            justifyContent: collapsed ? 'center' : 'initial',
                                            px: 2.5,
                                            whiteSpace: 'nowrap'
                                        }}>
                                        <ListItemIcon
                                            sx={{
                                                minWidth: 0,
                                                mr: collapsed ? 'auto' : 2,
                                                justifyContent: 'center'
                                            }}>
                                            {item.icon}
                                        </ListItemIcon>
                                        {!collapsed && (
                                            <ListItemText
                                                primary={item.label}
                                                sx={{
                                                    whiteSpace: 'nowrap',
                                                    overflow: 'hidden',
                                                    textOverflow: 'ellipsis',
                                                    display: collapsed ? 'none' : 'block',
                                                    opacity: collapsed ? 0 : 1,
                                                    transition: theme.transitions.create(['opacity'], {
                                                        easing: theme.transitions.easing.sharp,
                                                        duration: theme.transitions.duration.shorter
                                                    }),
                                                    ml: 0.5 // 增加左边距，避免文字太靠近图标
                                                }}
                                            />
                                        )}
                                    </ListItemButton>
                                </Tooltip>
                            ))}
                        </List>
                    </Box>
                </Drawer>

                {/* 主内容区域 */}
                <Box
                    component="main"
                    sx={{
                        flexGrow: 1,
                        p: 3,
                        background: theme.palette.background.default,
                        display: 'flex',
                        flexDirection: 'column',
                        height: '100%',
                        overflow: 'auto'
                    }}>
                    <Container
                        maxWidth="xl"
                        sx={{
                            flexGrow: 1,
                            mb: 3
                        }}>
                        <Outlet />
                    </Container>
                </Box>
            </Box>

            {/* 页脚 */}
            <Box
                component="footer"
                sx={{
                    py: 1.5,
                    px: 2,
                    textAlign: 'center',
                    bgcolor: 'background.paper',
                    borderTop: '1px solid rgba(0, 0, 0, 0.06)'
                }}>
                <Typography variant="body2" color="text.secondary">
                    SME CDC SMS ©{new Date().getFullYear()} SME IT Support
                </Typography>
            </Box>
        </Box>
    );
};

export default MainLayout;
